package com.chuanyang.driverh.mainhome.adapter;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chuanyang.driverh.R;
import com.chuanyang.driverh.base.BaseListAdapter;
import com.chuanyang.driverh.mainhome.BidOrderActivity;
import com.chuanyang.driverh.mainhome.OrderDetailRceiveActivity;
import com.chuanyang.driverh.response2.ResultGetOrder;
import com.chuanyang.driverh.responseresult.OrderDatailResult;
import com.chuanyang.driverh.responseresult.Result;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.StringUtil;
import com.chuanyang.driverh.utils.eventbus.RefleshFragEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;


public class GetOrderListAdapter extends BaseListAdapter<ResultGetOrder.PageEntity.OrderEntity> {
    private Activity activity;
    private Dialog dialog;
    ResultGetOrder.PageEntity.OrderEntity chooseItem;

    public GetOrderListAdapter(Activity activity) {
        super(activity);//此处不传入集合，则默认集合长度为0，在setdataresult（）方法中，添加数据并刷新
        this.activity = activity;
    }

    @Override
    public View getZkView(final int position, View convertView, final ViewGroup parent) {
        ViewHolder viewHolder = null;
        if (convertView == null) {
            convertView = getInflater().inflate(R.layout.home_item_get_order, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.line_left = convertView.findViewById(R.id.line_left);
            viewHolder.tv_has_receive = (TextView) convertView.findViewById(R.id.tv_has_receive);
            viewHolder.tv_order_no = (TextView) convertView.findViewById(R.id.tv_order_no);
            viewHolder.tv_order_time = (TextView) convertView.findViewById(R.id.tv_order_time);
            viewHolder.tv_city_start = (TextView) convertView.findViewById(R.id.tv_city_start);
            viewHolder.tv_city_end = (TextView) convertView.findViewById(R.id.tv_city_end);
            viewHolder.tv_goods_name = (TextView) convertView.findViewById(R.id.tv_goods_name);
            viewHolder.tv_weight = (TextView) convertView.findViewById(R.id.tv_weight);
            viewHolder.tv_price = (TextView) convertView.findViewById(R.id.tv_price);
            viewHolder.tv_price_unit = (TextView) convertView.findViewById(R.id.tv_price_unit);
            viewHolder.tv_load = (TextView) convertView.findViewById(R.id.tv_load);
            viewHolder.tv_time_load = (TextView) convertView.findViewById(R.id.tv_time_load);
            viewHolder.tv_unload = (TextView) convertView.findViewById(R.id.tv_unload);
            viewHolder.tv_time_unload = (TextView) convertView.findViewById(R.id.tv_time_unload);
            viewHolder.tv_order_type = (TextView) convertView.findViewById(R.id.tv_order_type);
            viewHolder.tv_receive_order = (TextView) convertView.findViewById(R.id.tv_receive_order);
            viewHolder.tv_give_up = (TextView) convertView.findViewById(R.id.tv_give_up);
            viewHolder.tv_price_or_bidprice = (TextView) convertView.findViewById(R.id.tv_price_or_bidprice);
            viewHolder.tv_my_bid_price = (TextView) convertView.findViewById(R.id.tv_my_bid_price);
            viewHolder.tv_notice_no = (TextView) convertView.findViewById(R.id.tv_notice_no);
            viewHolder.ll_div = convertView.findViewById(R.id.ll_div);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        final ResultGetOrder.PageEntity.OrderEntity data = getItem(position);

        if (StringUtil.isBlank(data.getNoticeNo())){
            viewHolder.tv_notice_no.setVisibility(View.INVISIBLE);
        }else {
            viewHolder.tv_notice_no.setVisibility(View.VISIBLE);
            if (data.getNoticeNo().contains(",")){
                viewHolder.tv_notice_no.setText(data.getNoticeNo().substring(0,data.getNoticeNo().indexOf(",")-1)+"...");
            }else {
                viewHolder.tv_notice_no.setText(data.getNoticeNo());
            }
        }

        if (data.getFleetId() == 0 && data.getDriverId() == 0) {//待处理
            viewHolder.line_left.setBackgroundResource(R.color.text_baobiao);
            viewHolder.tv_has_receive.setTextColor(activity.getResources().getColor(R.color.text_baobiao));
            viewHolder.tv_has_receive.setText("待处理");
            viewHolder.tv_receive_order.setVisibility(View.VISIBLE);
            viewHolder.tv_give_up.setVisibility(View.VISIBLE);

        } else {//已接单
            viewHolder.line_left.setBackgroundResource(R.color.text_assign_car_blue);
            viewHolder.tv_has_receive.setTextColor(activity.getResources().getColor(R.color.text_assign_car_blue));
            viewHolder.tv_has_receive.setText("已接单");
            viewHolder.tv_receive_order.setVisibility(View.GONE);
            viewHolder.tv_give_up.setVisibility(View.GONE);

        }


      /*  if (data.getOrderType()==3){
            viewHolder.tv_give_up.setVisibility(View.VISIBLE);
        }else {
            if (data.getOrderStatus()>=1){
                viewHolder.tv_give_up.setVisibility(View.GONE);
            }else{
                viewHolder.tv_give_up.setVisibility(View.VISIBLE);
            }
        }*/

//        viewHolder.tv_time.setText(data.getExpiredTime());
        viewHolder.tv_order_no.setText(data.getOrderNo());
        viewHolder.tv_order_time.setText(data.getOrderTime());
        viewHolder.tv_city_start.setText(StringUtil.getSimpleMunicipality(data.getBeginCity()));
        viewHolder.tv_city_end.setText(StringUtil.getSimpleMunicipality(data.getEndCity()));
        setGoodName(viewHolder.tv_goods_name, data.getGoodss());//货品名称

        viewHolder.tv_weight.setText(StringUtil.getDouble(data.getSumGoodsWeight() + ""));

        if (data.getCurrency() == 2) {
            viewHolder.tv_price_unit.setText("$/t");
        } else {
            viewHolder.tv_price_unit.setText("¥/t");
        }


        if (data.getOrderType() == 1) {
            viewHolder.tv_price_or_bidprice.setText("最低竞价:");
            viewHolder.tv_price.setText(StringUtil.getDouble(data.getMinBid()+""));
            if (data.getCurrency() == 2) {
                viewHolder.tv_my_bid_price.setText("我的竞价" + StringUtil.getDouble(data.getBidPrice()+"" )+ "$/t");
            } else {
                viewHolder.tv_my_bid_price.setText("我的竞价" + StringUtil.getDouble(data.getBidPrice()+"") + "¥/t");
            }

            viewHolder.tv_receive_order.setText("重新竞价");



        } else {
         if (data.getPrice()!=null)  viewHolder.tv_price.setText(StringUtil.getDouble(data.getPrice()+""));
            viewHolder.tv_price_or_bidprice.setText("单价:");
            viewHolder.tv_my_bid_price.setText("");
            viewHolder.tv_receive_order.setText("接单");
        }










        viewHolder.tv_receive_order.setText("接单");
        if ((data.getType() ==2)) {//车队推送单
            if (data.getOrderType() == 1) {//1竞价
                viewHolder.tv_receive_order.setText("重新竞价");
                viewHolder.tv_order_type.setBackgroundResource(R.mipmap.order_bid_t);
            } else if (data.getOrderType() == 2) {//匹配
                viewHolder.tv_order_type.setBackgroundResource(R.mipmap.order_match_t);
            } else {//专线
                viewHolder.tv_order_type.setBackgroundResource(R.mipmap.order_special_t);
            }
        } else {//推送的个人单
            if (data.getOrderType() == 1) {//1竞价
                viewHolder.tv_receive_order.setText("重新竞价");
                viewHolder.tv_order_type.setBackgroundResource(R.mipmap.order_bid_p);

            } else if (data.getOrderType() == 2) {//匹配
                viewHolder.tv_order_type.setBackgroundResource(R.mipmap.order_match_p);
            } else {//专线
                viewHolder.tv_order_type.setBackgroundResource(R.mipmap.order_special_p);
            }
        }



     /*   viewHolder.tv_time_load.setText(data.getStartTime());
        if (!StringUtil.isBlank(data.getEndTime())) {
            viewHolder.tv_time_unload.setText(data.getEndTime());
        }else {
            viewHolder.tv_time_unload.setText("不限");
        }*/



        if (data.getTransPortWay() == 2)//船
        {
            viewHolder.tv_load.setText("装卸天数");
            viewHolder.tv_unload.setText("受载日期");
            viewHolder.tv_load.setPadding(6,0,6,0);
            viewHolder.tv_unload.setPadding(6,0,6,0);
            viewHolder.tv_load.setBackgroundResource(R.drawable.tv_shape_round_corner_load);
            viewHolder.tv_unload.setBackgroundResource(R.drawable.tv_shape_round_corner_unload);

            viewHolder.tv_time_load.setText(data.getStevedoreDay()+"天");
            viewHolder.tv_time_unload.setText(data.getStartTime()+"±"+data.getFq()+"天");
        }else  {
            viewHolder.tv_load.setText("提");
            viewHolder.tv_unload.setText("卸");
            viewHolder.tv_load.setPadding(0,0,0,0);
            viewHolder.tv_unload.setPadding(0,0,0,0);
            viewHolder.tv_load.setBackgroundResource(R.drawable.tv_point_load);
            viewHolder.tv_unload.setBackgroundResource(R.drawable.tv_point_unload);
            viewHolder.tv_time_load.setText(data.getStartTime());
            if (!StringUtil.isBlank(data.getEndTime())) {
                viewHolder.tv_time_unload.setText(data.getEndTime());
            }else {
                viewHolder.tv_time_unload.setText("不限");
            }

        }








        if (data.getOrderType() == 1) {//1竞价
            //重新竞价之后不显示重新竞价
            if (data.getOrderStatus()==0){
                viewHolder.tv_receive_order.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        requsetData(data);
                    }
                });
            }else {
                viewHolder.tv_receive_order.setVisibility(View.GONE);
            }
        } else {
            viewHolder.tv_receive_order.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    chooseItem = data;
//                    receiveOrder("1");
                    receiveOrder(data.getType()+"");
                   /* dialog = DialogUtil.myDialog(activity, "接单", "取消", "确定", "确定接单？", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (v.getId() == R.id.dialog_btn_right) {
                                receiveOrder("1");
                            }
                            dialog.cancel();
                        }
                    });*/

                }
            });
        }
        viewHolder.tv_give_up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog = DialogUtil.myDialog(activity, "放弃", "取消", "确定", "确定放弃订单？", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (v.getId() == R.id.dialog_btn_right) {
                            //放弃
                            if (data.getOrderType() == 1) {
                                orderDelete(data);
                            } else {
                                orderSheve(data.getOrderId() + "", "2", data.getFleetId() == 0 ? "1" : "2");
                            }
                        }
                        dialog.cancel();
                    }
                });
            }
        });
        viewHolder.ll_div.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, OrderDetailRceiveActivity.class);
                if (data.getOrderType() == 1) {//1竞价
                    if (data.getOrderStatus()>0){
                        intent.putExtra("type", "0");
                    }else {
                        intent.putExtra("type", "2");
                        intent.putExtra("minPrice", data.getBidPrice()+"");
                    }
                    intent.putExtra("bidId", data.getBidId() + "");
                } else {
                    if (data.getFleetId() == 0 && data.getDriverId() == 0) {//待处理
                        intent.putExtra("type", "4");//显示2个按钮
                        if (data.getType()==2) {
                            intent.putExtra("fleetOrPerson", "2");//显示2个按钮
                        }else {
                            intent.putExtra("fleetOrPerson", "1");//显示2个按钮
                        }
                    } else {
                        intent.putExtra("type", "0");//不显示按钮
                    }
                }
                intent.putExtra("data", data.getOrderId() + "");
                activity.startActivity(intent);
            }
        });
        return convertView;
    }

    private void setGoodName(TextView view, List<ResultGetOrder.PageEntity.OrderEntity.GoodssEntity> goodnames) {
        StringBuilder builder = new StringBuilder();
        for (ResultGetOrder.PageEntity.OrderEntity.GoodssEntity info : goodnames) {
            builder.append(info.getGoodsName() + ",");
        }
        String temp = builder.toString();
        String result = temp.substring(0, temp.length() - 1);
        view.setText(result);
    }


    private void receiveOrder(String type) {
        DialogUtil.showLoadingDialog(activity, "加载中...");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("orderId", chooseItem.getOrderId() + "");
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("type", type);
        params.put("orderType", chooseItem.getOrderType() + "");
//        params.put("amount", data.getOrder_Amount() + "");
        if (chooseItem.getAppoint() != null) {
            params.put("appoint", chooseItem.getAppoint() + "");
        } else {
            params.put("appoint", "1");
        }
        /*if (data.getOrderType()==3){
            params.put("appoint","1");
        }else  if (!StringUtil.isBlank( data.getAppoint())){
            params.put("appoint", data.getAppoint() + "");
        }*/


        MyHttpUtil.receiveOrder(activity, params, new MyCallback<Result>(activity, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activity, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
//                    activity.startActivity(new Intent(activity, GetOrderSuccessActivity.class).putExtra("data", data));
                    if (StringUtil.isBlank(result.getMsg())) {
                        PrintUtil.toast(activity, "操作成功");
                    } else {
                        PrintUtil.toast(activity, result.getMsg());
                    }
                    EventBus.getDefault().post(new RefleshFragEvent(1));
                } else {
                    PrintUtil.toast(activity, result.getMsg());
                }
            }
        });

    }

    //订单搁置
    private void orderSheve(String orderId, String oprateType, String pushType) {//操作类型（1：接单，2：拒绝，3：搁置）
        DialogUtil.showLoadingDialog(activity, "加载中...");
        Map<String, String> params = new HashMap<String, String>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("orderId", orderId);
        params.put("operate", oprateType);
        params.put("type", pushType);//类型（1：个人，2：车队）
        MyHttpUtil.orderShelve(activity, params, new MyCallback<OrderDatailResult>(activity, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activity, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(OrderDatailResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    if (StringUtil.isBlank(result.getMsg())) {
                        PrintUtil.toast(activity, "操作成功");
                    } else {
                        PrintUtil.toast(activity, result.getMsg());
                    }
                    EventBus.getDefault().post(new RefleshFragEvent(1));
                } else {
                    PrintUtil.toast(activity, result.getMsg());
                }

            }
        });
    }

    //竞价单放弃
    private void orderDelete(ResultGetOrder.PageEntity.OrderEntity data) {
        DialogUtil.showLoadingDialog(activity, "加载中...");
        Map<String, String> params = new HashMap<String, String>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("orderId", data.getOrderId() + "");
        params.put("bidId", data.getBidId());
        params.put("type", "1");
        MyHttpUtil.deletePendOrder(activity, params, new MyCallback<OrderDatailResult>(activity, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activity, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(OrderDatailResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    if (StringUtil.isBlank(result.getMsg())) {
                        PrintUtil.toast(activity, "操作成功");
                    } else {
                        PrintUtil.toast(activity, result.getMsg());
                    }
                    EventBus.getDefault().post(new RefleshFragEvent(0));
                } else {
                    PrintUtil.toast(activity, result.getMsg());
                }

            }
        });
    }

    class ViewHolder {
        View line_left;
        TextView tv_has_receive;
        TextView tv_order_no;
        TextView tv_order_time;
        TextView tv_city_start;
        TextView tv_city_end;
        TextView tv_goods_name;
        TextView tv_weight;
        TextView tv_price;
        TextView tv_price_unit;
        TextView tv_load;
        TextView tv_time_load;
        TextView tv_unload;
        TextView tv_time_unload;
        TextView tv_order_type;
        TextView tv_receive_order;
        TextView tv_give_up;
        TextView tv_price_or_bidprice;
        TextView tv_my_bid_price;
        TextView tv_notice_no;
        View ll_div;
    }


    private void requsetData(final ResultGetOrder.PageEntity.OrderEntity data) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("orderId", data.getOrderId() + "");
        MyHttpUtil.selectOrderMsgById(activity, params, new MyCallback<OrderDatailResult>(activity, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activity, "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(OrderDatailResult result, int id) {

                if (result.getCode() == ConstUtil.OK) {
                    Intent intent = new Intent(activity, BidOrderActivity.class);
                    intent.putExtra("data", result.getData());
                    intent.putExtra("bidId", data.getBidId());
                    activity.startActivity(intent);
//                    activity.startActivity(new Intent(activity,BidOrderActivity.class).putExtra("data",result.getData()));

                } else {
                    PrintUtil.toast(activity, result.getMsg());
                }
            }
        });

    }
}
